﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using Sunboxsoft.Common;
using Sunboxsoft.ASMS.Client.UI.Properties;

namespace Sunboxsoft.ASMS.Client.UI.Booking
{
    /// <summary>
    /// 显示预约单列表
    /// </summary>
    public partial class BookingBillListView : UserControl, IView
    {
        Promise _promise = new Promise();
        #region fileds
        private int _pageIndex;
        private int _pageCount;
        #endregion

        public BookingBillListView()
        {
            InitializeComponent();

            this.txtBeginDate.DateTime = DateTime.Now;
            this.txtEndDate.DateTime = DateTime.Now.AddMonths(1);

            ctlGrid.EmbeddedNavigator.ButtonClick += new DevExpress.XtraEditors.NavigatorButtonClickEventHandler(OnEmbeddedNavigatorButtonClick);
        }

        #region actions
        /// <summary>
        /// 查看
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnViewClick(object sender, object e)
        {
            if (this.ctlGridViewData.FocusedRowHandle > -1)
            {
                WebRef.VBookingBill item = this.ctlGridViewData.GetFocusedRow() as WebRef.VBookingBill;
                if (item != null)
                {
                    UIContext.Current.ViewManager.PopupView(new Show.ShowBookingBillDetail(item.Id), new PopupViewArgs("查看预约单信息"));
                }
            }
        }
        /// <summary>
        ///新建
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnCreateClick(object sender, object e)
        {
            UIContext.Current.ViewManager.PopupView(new Booking.SelectCustomerView(), new PopupViewArgs("新建预约单-选择客户"));
        }
        /// <summary>
        /// 接车派工
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnDispict_Click(object sender, object e)
        {
            if (this.ctlGridViewData.FocusedRowHandle > -1)
            {
                WebRef.VBookingBill item = this.ctlGridViewData.GetFocusedRow() as WebRef.VBookingBill;
                if (item != null)
                {
                    if (item.Status == Domain.Constant.BookingBillStatus.Normal)
                    {
                        UIContext.Current.ViewManager.PopupView(new Create.CreateMaintenanceBillView(item), new PopupViewArgs("接车派工"));
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowInfo("除待到店的预约单外，其他均不可接车派工！");
                    }
                }
            }
        }
        /// <summary>
        /// 预约单修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnEditClick(object sender, object e)
        {
            if (this.ctlGridViewData.FocusedRowHandle > -1)
            {
                WebRef.VBookingBill item = this.ctlGridViewData.GetFocusedRow() as WebRef.VBookingBill;
                if (item != null)
                {
                    if (item.Status == Domain.Constant.BookingBillStatus.Normal)
                    {
                        UIContext.Current.ViewManager.PopupView(new Edit.UpdateBookingBillView(item.Id), new PopupViewArgs("修改预约单信息"));
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowInfo("除待到店的预约单外，其他均不可编辑！");
                    }
                }
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnBtnCancelClick(object sender, object e)
        {
            if (this.ctlGridViewData.FocusedRowHandle > -1)
            {
                WebRef.VBookingBill item = this.ctlGridViewData.GetFocusedRow() as WebRef.VBookingBill;
                if (item != null)
                {
                    if (item.Status == Domain.Constant.BookingBillStatus.Normal)
                    {
                        if (UIContext.Current.ViewManager.ShowQuestion("确定要取消此预约吗？"))
                        {
                            DeleteBookingBill(item.Id);
                        }
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowInfo("除待到店的预约单外，其他均不可取消！");
                    }
                }
            }
        }
        private void OnEmbeddedNavigatorButtonClick(object sender, DevExpress.XtraEditors.NavigatorButtonClickEventArgs e)
        {
            if (e.UpdatePageIndex(_pageCount, ref _pageIndex))
            {
                LoadBookingBillPagedData();
            }
        }
        /// <summary>
        /// 刷新按钮被点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnRefreshActionClick(object sender, object e)
        {
            _pageIndex = 0;
            LoadBookingBillPagedData();
        }
        #endregion

        #region methods
        private void LoadBookingBillPagedData()
        {
            DateTime beginTime;
            DateTime endTime;
            if (!GetDateRange(out beginTime, out endTime))
            {
                UIContext.Current.ViewManager.ShowWarning("请选择正确的日期范围!");
            }

            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                PagedResult<WebRef.VBookingBill> result = new Service.QueryService().QueryBookingBillPagedList(ModuleContext.Current.BusinessId.Value,
                    ModuleContext.Current.StationId.Value,
                    beginTime,
                    endTime,
                    GetSalesManagerId(),
                    GetStatus(),
                    _pageIndex * GetPageLimit(), GetPageLimit());
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        //binding
                        this.ctlGrid.Paginate<WebRef.VBookingBill>(result, out _pageIndex, out _pageCount);
                        _promise.Resolve();
                    }
                    else
                    {
                        MessageBox.Show(result.Message);
                        _promise.Reject();
                    }
                    this.HideMask();
                }));
            });
        }

        private int GetPageLimit()
        {
            return 25;
        }

        /// <summary>
        /// 获取查询时间范围，并验证时间范围是否符合要求
        /// </summary>
        /// <param name="beginTime"></param>
        /// <param name="endTime"></param>
        /// <returns>true:时间范围符合要求，false：时间范围不符合要求</returns>
        private bool GetDateRange(out DateTime beginTime, out DateTime endTime)
        {
            beginTime = Convert.ToDateTime(txtBeginDate.DateTime.ToShortDateString());
            endTime = Convert.ToDateTime(txtEndDate.DateTime.ToShortDateString());
            if (beginTime >= endTime)
            {
                return false;
            }
            return true;
        }

        public int GetStatus()
        {
            Domain.IntCodeTextItem item = ctlLookUpStatus.GetSelectedDataRow() as Domain.IntCodeTextItem;
            if (item == null)
            {
                return Domain.Constant.BookingBillStatus.All;
            }
            return item.Code;
        }

        public Guid? GetSalesManagerId()
        {
            WebRef.VStaffPosition item = SearchLookUpEditUtil.GetSelectedValue<WebRef.VStaffPosition>(this.ctlLookupSalesManager);
            if (item == null)
            {
                return null;
            }
            return item.StaffId;
        }
        /// <summary>
        /// 取消预约单
        /// </summary>
        private void DeleteBookingBill(Guid bookingBillId)
        {
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                ServiceResult result = new Service.DeleteService().DeleteBookingBill(bookingBillId);
                this.BeginInvoke(new Action(() =>
                {
                    if (result.IsSuccess)
                    {
                        LoadBookingBillPagedData();
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                    this.HideMask();
                }));
            });
        }
        #endregion

        #region IView 成员

        public void RegisterAction(ActionNodeCollection collection)
        {
            collection
                .AddAction(new ActionNode("view", Resources.isView, "查看", OnBtnViewClick))
                .AddAction(new ActionNode("create", Resources.isBooking, "新增", OnBtnCreateClick))
                .AddAction(new ActionNode("dispict", Resources.isDispatchingBookList, "接待开单", OnBtnDispict_Click))
                .AddAction(new ActionNode("edit", Resources.isEdit, "修改", OnBtnEditClick))
                .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", OnBtnCancelClick))
                .AddAction(new ActionNode("refresh", Resources.isRefresh, "刷新", OnRefreshActionClick));
        }

        public void Active(ViewActiveArgs args)
        {
            LookUpEditUtil.BindIntCodeTextItem(ctlLookUpStatus, Domain.Constant.BookingBillStatus.Enumerate(), Domain.Constant.BookingBillStatus.AllItem);
            _promise.Then(() =>
            {
                this.ctlLookupSalesManager.BindVStaffPosition(_promise, Domain.Constant.StaffPosts.SalesManager, false, true);
            }).Then(LoadBookingBillPagedData).Run();
        }

        public void Resume(ViewResumeArgs args)
        {
            if (args.ClosedArgs.Result)
            {
                LoadBookingBillPagedData();
            }
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("预约单列表");
        }
        #endregion
    }
}
